package com.luck.easyfoodbatch.mvp.mine;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;

import com.luck.easyfoodbatch.callback.JsonCallback;
import com.luck.easyfoodbatch.mvp.model.UploadModel;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.lzy.okhttputils.model.HttpParams;
import com.lzy.okhttputils.request.PostRequest;

import java.io.File;
import java.util.List;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;

/**
 * author：luck
 * project：EasyFoodBatch
 * package：com.luck.easyfoodbatch.mvp.mine
 * email：893855882@qq.com
 * data：16/10/20
 */
public class UploadSinglePresenter implements UploadImageModel {
    private final String TAG = "UploadSinglePresenter";
    private UploadImageView uploadImageView;
    private Context mContext;

    public UploadSinglePresenter(UploadImageView uploadImageView, Context mContext) {
        this.uploadImageView = uploadImageView;
        this.mContext = mContext;
    }

    @Override
    public void uploads(int type, File file, List<File> files) {
        OkHttpUtils instance = OkHttpUtils.getInstance();
        PostRequest request = instance.post(HttpUtil.UPLOADS);
        HttpParams params = new HttpParams();
        request.tag(this);
        request.cacheMode(CacheMode.DEFAULT);// 缓存模式
        request.cacheKey(TAG);
        switch (type) {
            case 0:
                // 上传单张图片
                params.put("img", file);
                request.params(params);
                break;
            case 1:
                // 上传多张
                request.addFileParams("img",files);
                break;
        }
        request.execute(new JsonCallback(mContext, UploadModel.class) {
            @Override
            public void onResponse(boolean isFromCache, Object data, Request request, @Nullable Response response) {
                uploadImageView.uploadSuccess((UploadModel) data);
                uploadImageView.hideLoading();
            }

            @Override
            public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                super.onError(isFromCache, call, response, e);
                uploadImageView.hideLoading();
                uploadImageView.httpStatusError();
            }

            @Override
            public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                uploadImageView.upProgress(currentSize, totalSize, progress, networkSpeed);
            }
        });
    }
}
